import Vue from 'vue'
import router from '@/router'

const authFuntion = (to, from, next) => {
  //根据字段判断是否进行路由过滤（即是否需要登录才能访问）
  if (to.meta.white == true) {
    next()
    return
  }

  let userId = localStorage.getItem('userId')
  let card_stats = localStorage.getItem('card_stats')

  if (userId != null && card_stats == 1) {
    if (to.name == 'LoggingPage') {
      next({path: '/'})
    } else {
      next()
    }
  } else if (userId != null && card_stats == 0) {
    Vue.prototype.$inbound.invoke({
      interfaceId: 'app.member.queryCardStats',
      data: {user_id: userId}
    }).then(v => {
      localStorage.setItem("card_stats", v.card_stats)
      if (v.card_stats == 0) {
        next({name: 'BindingPage'})
      } else {
        next({path: '/'})
      }
    })
  } else {
    //防止无限循环
    if (to.name == 'LoggingPage') {
      next()
      return
    }
    next({name: 'LoggingPage'})
  }
}

export default {
  install: function () {
    router.beforeEach(authFuntion)
  }
}
